<template>
  <span
    v-for="option in currOption"
    :class="option.color ? 'ac-dict-color-label' : 'ac-dict-label'"
    :style="option.color ? 'background: ' + option.color : ''"
  >{{option.value}}</span>
</template>

<script setup>
import { ref, watch } from 'vue';
import { getDictionary } from '@/utils/system';

const props = defineProps({
  dictCode: String,
  dictValue: [String, Array],
});

const options = ref([]);
const currOption = ref([]);

const init = async() => {
  currOption.value = [];
  await loadDicAndShow(props.dictCode);

  let values;
  if (Array.isArray(props.dictValue)) {
    values = props.dictValue;
  } else {
    values = [props.dictValue || ''];
  }

  options.value.forEach(option => {
    if (values.find(value => option.key === value)) {
      currOption.value.push(option);
    }
  });
};

const loadDicAndShow = async(dictCode) => {
  if ((dictCode || '') === '') {
    options.value = [];
  } else {
    options.value = await getDictionary(dictCode);
  }
};

watch(() => props, () => {
  init();
}, {immediate: true, deep: 1});
</script>

<style scoped>
.ac-dict-color-label {
  border-radius: 5px;
  height: 24px;
  line-height: 24px;
  padding: 4px 6px;
  color: white;
}
.ac-dict-label {
  margin-right: 10px;
}
.ac-dict-label:last-child {
  margin-right: 0;
}
</style>